﻿using UnityEngine;
using System.Collections;

public class Controller : MonoBehaviour 
{
	public delegate void FloatDelegate (float f);
	public FloatDelegate OnInputAngle;
	public GameObject m_cueBall;

	private Vector3 m_mousePos2D;
	private Vector3 m_mousePos3D;

	public Vector3 MousePos3D { get { return m_mousePos3D;} }
	public GameObject CueBall { get { return m_cueBall; } }

	void Start ()
	{
		Initialize();
	}

	void Update ()
	{
		InputAngleEvent();
	}

	public void Initialize ()
	{
		m_mousePos2D = new Vector3(float.NaN, float.NaN, float.NaN);
		m_mousePos3D = new Vector3(float.NaN, float.NaN, float.NaN);
	}

	public float GetInputAngle (Vector3 direction)
	{
		Vector3 r = direction.normalized;
		float angle = angle = r.x > 0 ? Mathf.Asin(r.z) : Mathf.PI - Mathf.Asin(r.z);
		return (angle * 180f / Mathf.PI + 180f) % 360;
	}

	public Vector3 GetInputDirection (float angle)
	{
		angle = angle * Mathf.PI / 180f;
		return new Vector3(-Mathf.Cos(angle), 0f, -Mathf.Sin(angle));
	}

	private void InputAngleEvent ()
	{
		if (Input.GetMouseButtonDown(0))
		{
			m_mousePos2D = Input.mousePosition;
			m_mousePos3D = Camera.main.ScreenToWorldPoint(new Vector3(m_mousePos2D.x, m_mousePos2D.y, 14.5f));

			if (OnInputAngle != null)
			{
				OnInputAngle(GetInputAngle(m_mousePos3D-m_cueBall.transform.position));
			}
		}
	}
}
